﻿<?PHP
require_once("base.wpfb.php");
require_once ('src/facebook.php');

class SimpleTextbox{

private $globalVars = null;
private $entryPageName = null;

public function __construct($pageParent) {
	$this->globalVars = new WPFB($pageParent);
	$this->entryPageName = $pageParent;
}

public function publishFromWordpressPostID()
{
	if( isset($_GET['post_id']) && isset($_GET['fburl']) )
	{
		try{
			if( is_numeric($_GET['post_id']) == false)
				throw new Exception('Post ID must be numeric');

			$query = get_post($_GET['post_id']);
			if( !$query->guid )
				throw new Exception("Database error: There is no such post having id = {$_GET['post_id']}");
			
			$completeOrExcerpt = isset($_GET['post_as']) && $_GET['post_as'] != 'embed';
			
			$dataForFacebook = array();
			
			$first50Words = null;
			$array = explode(' ', $query->post_content);
			if (count($array)<= 50) {
				$first50Words = $string;
			}
			else {
				array_splice($array, 50);
				$first50Words = implode(' ', $array).' ...';
			}
			$categories = get_the_category($query->ID);
			$title = $categories[0]->name . ' নিয়ে: ' . get_the_author_meta('display_name', $query->post_author);
			$msg .= $completeOrExcerpt ? $query->post_content : $first50Words;
			$dataForFacebook['message'] = "***" . $title . "***" . PHP_EOL . PHP_EOL . $msg;
			
			if($completeOrExcerpt == false)
			{
				$dataForFacebook['name'] = get_the_title($query->ID);
				$dataForFacebook['caption'] = get_bloginfo('url');
				$dataForFacebook['link'] = $query->guid;
				$dataForFacebook['description'] = $msg;
				if(has_post_thumbnail($query->ID))
					$dataForFacebook['picture'] =  wp_get_attachment_url( get_post_thumbnail_id($query->ID));
				else
				{
					$dataForFacebook['picture'] = 'http://www.gravatar.com/avatar/' . md5(rand().'@example.com') . '.jpg?s=128&d=identicon';
				}
			}
			$dataForFacebook['actions'] = array(
				array(
					'name' => 'আমাদের হোমপেজ: ' . strtoupper(parse_url(get_bloginfo('siteurl'), PHP_URL_HOST)),
					'link' => get_bloginfo('siteurl')
				)
			);
			
			$url = $_GET['fburl'];
			$response = $this->publishMsgToFacebook($title, $url, $dataForFacebook);
		}catch(Exception $e)
		{ 
			$this->globalVars->printException($e);
		}
	}
	?>
	<style type='text/css'>
	.wpfbPluginLabel{ font-weight:bold; padding-top: 10px; }
	</style>
	<h1>Insert the wordpress post id below</h1>
	<form action="<?php echo get_bloginfo('wpurl') . '/wp-admin/admin.php?page=' . $this->entryPageName ?>" method="GET">
		<label class='wpfbPluginLabel'>Wordpress post's url:</label><br/>
		<?PHP bloginfo('siteurl'); ?>/archives/
		<input class="title" name="post_id" type="text" value='-1' size="10" onclick='select()' noBanglaText='noBanglaText' /> <br/>
		
		<label class='wpfbPluginLabel'>Publish as:</label><br/>
		<input type="radio" name="post_as" value="embed" checked='checked' />Excerpt of the post 
		<input type="radio" name="post_as" value="basic" />Complete post<br/>
		
		<label class='wpfbPluginLabel'>Facebook url to post:</label><br/> 
		<input class="title" name="fburl" type="text" value='/1386757781551086/feed' noBanglaText='noBanglaText' onclick='select()' />
		<input type='hidden' name='page' value='<?PHP echo $this->entryPageName; ?>' />
		
		<br/><br/>
		<input class="button button-primary" type='submit' value='submit' />
	</form>
	<?PHP
}

private function updateAccessTokenIfNecessary($path){
	try{
		$edge = explode("/", $path);
		if($path[0] == '/')
			$index= 1;
		else
			$index = 0;
		$url = $edge[$index]."?fields=id";
		
		$jsonData = $this->globalVars->fetchURL($url);
		$checkAgainstId = $jsonData['id'];
		
		$url = "me/accounts";
		$jsonData = $this->globalVars->fetchURL($url);
		$json = $jsonData['data'];
		foreach($json as $val)
		{
			if($val['id'] == $checkAgainstId)
			{
				echo "<h2><strong>'{$edge[$index]}'</strong> belongs to another account which you manage: <strong>'{$val['name']}'</strong>. So you will post onbehalf of this account.</h2><hr/>";
				$this->globalVars->facebook->setAccessToken($val['access_token']);
			}
		}
	}catch(Exception $e)
	{}
}

private function publishMsgToFacebook($msg, $url, $dataForFacebook)
{
	$this->updateAccessTokenIfNecessary($url);	
	
	$response = $this->globalVars->postURL($url, $dataForFacebook);
	
	$idArray= explode('_', $response['id']);
	$url = "https://www.facebook.com/{$idArray[0]}/posts/{$idArray[1]}";
	echo "<h2>Post inserted as: <a target='_blank' href='$url'>$url</a></h2><hr/>";
}

public function terminalPost()
{
	array_walk_recursive($_POST, create_function('&$val', '$val = stripslashes($val);'));
	$fakeCall = $this->globalVars->fetchURL('/me/');
	
	try{
		$databaseRowsAsTR = null;
		if ( isset($_POST["fbposturi-name"]) && isset($_POST["msg-name"]) && isset($_POST["title-name"]) )
		{
			$url = $_POST["fbposturi-name"];
			$msg = '*** ' . $_POST["title-name"] . ' ***' . PHP_EOL . PHP_EOL . $_POST["msg-name"];
			$dataForFacebook = array(
				'message' => $msg,
				'actions' => array(
					array(
						'name' => 'আমাদের হোমপেজ: BUETian.com',
						'link' => 'http://www.buetian.com'
					)
				)
			);
			$response = $this->publishMsgToFacebook($msg, $url, $dataForFacebook);
			
			/* Insert into wordpress */
			if( isset($_POST['post2wp']) && $_POST['post2wp'] == 'yes' )
			{
				global $current_user;
				$my_post = array(
					'post_title' => $_POST['title-name'],
					'post_content' => $_POST['msg-name'],
					'tags_input' => explode(',', $_POST['tags-name']),
					'post_author' => $current_user->ID
				);
				
				$post_id = wp_insert_post( $my_post, $wp_error );
				if($wp_error)
					throw new Exception($wp_error->get_error_message());
					
				$url = get_bloginfo('wpurl') . "?p=$post_id";
				ECHO "<h2>Successfully posted and having 'draft' status in web: <a target='_blank' href='$url'>$url</a></h2><hr/>";
			}
		}
		$this->terminalPost_UI();
	}catch(Exception $e)
	{ 
		$this->globalVars->printException($e);
		$this->terminalPost_UI();
	}
} // function ends here


private function terminalPost_UI()
{ 
	/*
	if (count($groupList) == 0 )
		throw new Exception('Please save some data into server first');
	*/
?>
	<script type="text/javascript" src="//bangla-keyboard-layout.googlecode.com/files/rokeya_layout-4.4.73.js"></script>
	
	<h1>Insert new post here</h1>
	<style type='text/css'>
		.form label, .submit-button-right{ float:right; padding-right: 10px; }
	</style>
	<form action="<?php echo get_bloginfo('wpurl') . '/wp-admin/admin.php?page=' . $this->entryPageName ?>" method="post">
		<table class="form">
			<tr>
				<th><label for="input-one"><strong>Title:</strong></label></th>
				<td><input class="title" name="title-name" type="text" size="60" /></td>
			</tr>

			<tr>
				<th><label for="input-two"><strong>Tags/Original link<br/> (comma separated):</strong></label></th>
				<td><input class="tags" name="tags-name" type="text" size="60" /></td>
			</tr>
			
			<tr>
				<th><label for="input-two"><strong>Facebook post URL:</strong></label></th>
				<td><input class="tags" name="fbposturi-name" noBanglaText='noBanglaText' type="text" size="60" value='/1386757781551086/feed'  onclick='select()' /></td>
			</tr>
			
			<tr>
				<th><label for="input-two"><strong>Post as wordpress post:</strong></label></th>
				<td>
				<input type="radio" name='post2wp' value="yes" />Yes
				<input type="radio" name='post2wp' value="no" checked />No
				</select>
				</td>
			</tr>

			<tr>
				<th class="message-up"><label for="message"><strong>Message:</strong></label></th>
				<td>
				<textarea name="msg-name" id="message" cols="60" rows="10"></textarea>
				</td>
			</tr>

			<input type='hidden' name='page' value='<?PHP echo $this->entryPageName; ?>' />
			
			<tr>
				<th></th>
				<td class="submit-button-right" colspan="2"><input class="submit-text" type="submit" value="Publish inputs" /></td>
			</tr>
		</table>
	</form>
	
	<script type='text/javascript'>
	// hook all textbox with conditions
	var $textbox= jQuery("input:text, textarea").not('[noBanglaText]');
	jQuery.each($textbox,function(index,valueOfElement){
		if(this.id == '')
		{
			this.id= Math.random();
		}
		new banglaLayout(this.id);
	});
	</script>
<?PHP 
}

private function showGroupInformationListFromDatabase($group_id,$sort_order)
{
	$databaseRows = $this->globalVars->select_KCVPWEFCMV495KL($group_id,$sort_order);
	$databaseRowsAsTR = "";
	
	if( count($databaseRows) > 0)
	{
		foreach ($databaseRows as $rows)
		{
			$databaseRowsAsTR .= '<tr>';
			$databaseRowsAsTR .= "<td>{$rows['from_name']}</td>";
			$databaseRowsAsTR .= "<td>". htmlspecialchars($rows['message']) . "</td>";
			$databaseRowsAsTR .= "<td>{$rows['like_count']}</td>";
			$databaseRowsAsTR .= "<td><a target='_blank' href='{$rows['message_permalink']}'>{$rows['message_creation_time']}</a></td>";
			$databaseRowsAsTR .='</tr>';
		}
		//print_r($databaseRows);
	}
	return $databaseRowsAsTR;
}

} // class ends here
?>